/**
 * Filename: StatusDetailActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/3 10:54
 */
package com.github.postsanf.yinian.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.DetailAdapter;
import com.github.postsanf.yinian.adapter.LookHistoryAdapter;
import com.github.postsanf.yinian.adapter.StatusDetialAdapter;
import com.github.postsanf.yinian.bean.YNComment;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCommentResponse;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.entity.YNLoginResponse;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.github.postsanf.yinian.view.DetailRecyclerView;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 动态详情
 */
public class StatusDetailActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView mRecyclerView;
    private StatusDetialAdapter mAdapter;
    private List<YNComment> mCommentList = new ArrayList<>();
    private YNStatus mCurStatus;
    private int groupid;
    private SimpleDraweeView iv_detail_content;
    private DetailRecyclerView dRecyclerView;
    private DetailAdapter dAdapter;
    private List<String> mUrls = new ArrayList<>();
    private View topView;
    private LinearLayout ll_status_detail_content;
    private TextView tv_status_detail_content;
    private Button btn_comment;
    private EditText et_comment;
    private boolean isSending = false;                  //  是否在发布评论  默认 否
    private String cContent;
    private YNUser commentedUser;
    private AlertDialog alertDialog;
    private YNComment mCommentItem;
    private YNUser sys = new YNUser();
    private int pageIndex = 0;
    private RelativeLayout rl_comment;
    private RelativeLayout rl_look;
    private RecyclerView look_recycler_horizontal;
    private ImageView statusdetail_more;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_status_detail);
        registerBroadcastReceiver();
        initDatas();
        initView();
    }

    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTIONs.actionCloseAlbum);
        registerReceiver(MyReceiver, intentFilter);
    }

    BroadcastReceiver MyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case ACTIONs.actionCloseAlbum:
                    finish();
                    break;
            }
        }
    };

    private void initDatas() {
        mCurStatus = YNSingleton.getInstance().getCurStatus();
        groupid = application.getCurGid();
        if (getIntent() != null && getIntent().getIntExtra("adapterPage", 0) == 1) {
            mCommentList = mCurStatus.getComments();
        }
        sys.setUserid(CommonConstants.SYSTEM_ID);
        commentedUser = sys;
    }


    private void getUserAvatar(int userid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNLoginResponse resUser = gson.fromJson(s, YNLoginResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            String avatarPic = resUser.getData().get(0).getUpic();
                            Intent intent = getIntent();
                            if (intent != null) {
                                String lookStatus = intent.getStringExtra("lookPeople");
                                if (TextUtils.equals(lookStatus, "lookPeople")) {
                                    rl_comment.setVisibility(View.GONE);
                                    rl_look.setVisibility(View.VISIBLE);
                                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(StatusDetailActivity.this);
                                    linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                                    look_recycler_horizontal.setLayoutManager(linearLayoutManager);
                                    LookHistoryAdapter lookHistoryAdapter = new LookHistoryAdapter(StatusDetailActivity.this, mCurStatus, String.valueOf(application.getCurID()), avatarPic);
                                    look_recycler_horizontal.setAdapter(lookHistoryAdapter);
                                } else if (TextUtils.equals(lookStatus, "news")) {
                                    rl_comment.setVisibility(View.GONE);
                                } else {
                                    rl_comment.setVisibility(View.VISIBLE);
                                    rl_look.setVisibility(View.GONE);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void initView() {
        findViewById(R.id.top_back).setOnClickListener(this);
        statusdetail_more = ((ImageView) findViewById(R.id.statusdetail_more));
        statusdetail_more.setOnClickListener(this);
        rl_comment = ((RelativeLayout) findViewById(R.id.rl_comment));
        rl_look = ((RelativeLayout) findViewById(R.id.rl_look));
        look_recycler_horizontal = ((RecyclerView) findViewById(R.id.look_recycler_horizontal));
        getUserAvatar(application.getCurID());
        topView = View.inflate(this, R.layout.yn_include_status_detail_top, null);
        iv_detail_content = (SimpleDraweeView) topView.findViewById(R.id.iv_detail_content);
        dRecyclerView = (DetailRecyclerView) topView.findViewById(R.id.rv_detail_horizontal);
        ll_status_detail_content = (LinearLayout) topView.findViewById(R.id.ll_status_detail_content);
        tv_status_detail_content = (TextView) topView.findViewById(R.id.tv_status_detail_content);
        btn_comment = (Button) findViewById(R.id.btn_comment);
        et_comment = (EditText) findViewById(R.id.et_comment);
        btn_comment.setOnClickListener(this);
        if (mCurStatus.getEtext() != null && mCurStatus.getEtext().length() > 0) {
            ll_status_detail_content.setVisibility(View.VISIBLE);
            tv_status_detail_content.setText(mCurStatus.getEtext());
        }
        mUrls.addAll(mCurStatus.getUrl());
        WrapContentLinearLayoutManager horLayoutManager = new WrapContentLinearLayoutManager(this);
        horLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        dRecyclerView.setLayoutManager(horLayoutManager);
        dAdapter = new DetailAdapter(this, mUrls);
        dRecyclerView.setHasFixedSize(true);
        dRecyclerView.setAdapter(dAdapter);

        mRecyclerView = (RecyclerView) findViewById(R.id.rv_status_detail_list);
        WrapContentLinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mAdapter = new StatusDetialAdapter(this, mCommentList, groupid);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setHeaderView(topView);

        dRecyclerView.setOnItemScrollChangeListener(new DetailRecyclerView.OnItemScrollChangeListener() {
            @Override
            public void onChange(View view, int position) {
                if (position == -1) {
                    position = 0;
                }
                pageIndex = position;
                String path = YNUrlHelper.getStatusUrl(StatusDetailActivity.this, mUrls.get(position));
                Uri uri = Uri.parse(StringUtils.repaceImgUrl(path));
                ImageOptHelper.showFrescoStatusSingle(uri, iv_detail_content, StatusDetailActivity.this);
            }
        });
        if (mUrls.size() > 0) {
            String path = YNUrlHelper.getStatusUrl(StatusDetailActivity.this, mUrls.get(0));
            Uri uri = Uri.parse(StringUtils.repaceImgUrl(path));
            ImageOptHelper.showFrescoStatusSingle(uri, iv_detail_content, StatusDetailActivity.this);
        }
        dAdapter.setOnItemClickLitener(new DetailAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                pageIndex = position;
                String path = YNUrlHelper.getStatusUrl(StatusDetailActivity.this, mUrls.get(position));
                Uri uri = Uri.parse(StringUtils.repaceImgUrl(path));
                ImageOptHelper.showFrescoStatusSingle(uri, iv_detail_content, StatusDetailActivity.this);
            }
        });
        iv_detail_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                YNSingleton.getInstance().setCurStatus(mCurStatus);
                startActivity(new Intent(StatusDetailActivity.this, BrowseActivity.class).putExtra(CommonConstants.YNPOSITION, pageIndex));
            }
        });

        //为每个item增加响应事件
        mAdapter.setOnItemClickListener(new StatusDetialAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, YNComment data) {
                mCommentItem = data;
                if (mCommentItem.getCommentUser().getUserid() == application.getCurID() || String.valueOf(application.getCurID()).equals(getString(R.string.numberofme))) {
                    popDelComment();
                } else {
                    publishComment();
                }
            }
        });
    }

    private void popDelComment() {
        View sexView = View.inflate(this, R.layout.yn_comment_del, null);
        LinearLayout ll_ret = (LinearLayout) sexView.findViewById(R.id.ll_comment_ret);
        LinearLayout ll_del = (LinearLayout) sexView.findViewById(R.id.ll_comment_del);

        alertDialog = new AlertDialog.Builder(this).show();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.setContentView(sexView);
        WindowManager.LayoutParams layout = alertDialog.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 32 * 2);
        alertDialog.getWindow().setAttributes(layout);
        // 回复
        ll_ret.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publishComment();
                alertDialog.dismiss();
            }
        });
        // 删除
        ll_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delComment(mCommentItem.getCid());
                alertDialog.dismiss();
            }
        });
    }

    // 删除评论
    private void delComment(final String comId) {
        if (StringUtils.isEmptyString(comId)) {
            showToast("删除失败");
            return;
        }
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_DEL_COMMENT, comId);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynDelComment)).setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resDelComment = gson.fromJson(s, YNCommonResponse.class);
                        if (resDelComment != null && ReqUtils.isSuccess(resDelComment.getCode())) {
                            for (int i = 0; i < mCurStatus.getComments().size(); i++) {
                                if (comId.equals(mCurStatus.getComments().get(i).getCid())) {
                                    mCurStatus.getComments().remove(i);
                                    mAdapter.notifyItemRemoved(i + 1);
                                    mRecyclerView.scrollToPosition(i);
                                    // 通知评论更新
                                    Intent mIntent = new Intent(ACTIONs.actionComment);
                                    sendBroadcast(mIntent);
                                }
                            }
                        } else {
                            showToast(resDelComment.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void publishComment() {
        commentedUser = mCommentItem.getCommentUser();
        et_comment.setHint("//@" + mCommentItem.getCommentUser().getUnickname() + ":");
        et_comment.setFocusable(true);
        et_comment.setFocusableInTouchMode(true);
        et_comment.requestFocus();
        et_comment.findFocus();
    }

    // 发表评论
    private void doComment() {
        if (checkComment() && !isSending) {
            isSending = true;       // 更改状态
            LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
            mParam.put(CommonConstants.YNS_COMMENT_USER_ID, String.valueOf(application.getCurID()));
            mParam.put(CommonConstants.YNS_COMMENTED_USER_ID, String.valueOf(commentedUser.getUserid()));
            mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(mCurStatus.getEid()));
            mParam.put(CommonConstants.YNS_CONTENT, cContent);
            StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynSendComment)).setMethod(HttpMethods.Post).setParamMap(mParam)
                    .setHttpListener(new HttpListener<String>(true, false, true) {
                        @Override
                        public void onSuccess(String s, Response<String> response) {
                            YNCommentResponse resSendComment = gson.fromJson(s, YNCommentResponse.class);
                            if (resSendComment != null && ReqUtils.isSuccess(resSendComment.getCode())) {
                                YNComment createComment = resSendComment.getData().get(0);
                                createComment.setCcontent(cContent);
                                application.getCurUser().setUserid(application.getCurID());
                                createComment.setCommentUser(application.getCurUser());
                                createComment.setCommentedUser(commentedUser);
                                createComment.setCtime(DateFormat.format("yyyy-MM-dd  HH:mm:ss", new Date()).toString());
                                mCurStatus.getComments().add(mCurStatus.getComments().size(), createComment);
                                mAdapter.notifyItemInserted(mCurStatus.getComments().size());
                                mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
                                // 通知评论更新
                                Intent mIntent = new Intent(ACTIONs.actionComment);
                                sendBroadcast(mIntent);
                                et_comment.setHint("发表评论");
                                et_comment.setText("");
                                // 还原当前对系统的评论
                                commentedUser = sys;
                            } else {
                                showToast(resSendComment.getMsg());
                            }
                            // 还原状态
                            isSending = false;
                        }

                        @Override
                        public void onFailure(HttpException e, Response<String> response) {
                            showToast(CommonConstants.YN_NET_LINK);
                            // 还原状态
                            isSending = false;
                        }
                    });
            liteHttp.executeAsync(req);
        }
    }

    // 检测评论
    private Boolean checkComment() {
        cContent = et_comment.getText().toString().trim();
        if (StringUtils.isEmptyString(cContent)) {
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_comment:
                doComment();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.statusdetail_more:
                showPP(v);
                break;
            case R.id.pp_edit:
                YNSingleton.getInstance().setCurStatus(mCurStatus);
                Intent meditIntent = new Intent(StatusDetailActivity.this, PublishWithLocationActivity.class);
                meditIntent.putExtra("edit", "edit");
                startActivity(meditIntent);
                break;
            case R.id.pp_delete:
                new AlertDialog.Builder(this).setMessage("确定要删除动态详情吗？")
                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                doDeleteStatus();
                            }
                        })
                        .setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
                break;
            case R.id.pp_share:
                Intent intent = new Intent(StatusDetailActivity.this, SharePhotoActivity.class);
                intent.putStringArrayListExtra(ACTIONs.aAddData, (ArrayList<String>) mCurStatus.getUrl());
                startActivity(intent);
                break;
        }
    }

    private PopupWindow window;

    protected void showPP(View parent) {
        View v = LayoutInflater.from(StatusDetailActivity.this).inflate(R.layout.mcard_detail_pp,
                null);
        View pp_line1 = v.findViewById(R.id.pp_line1);
        View pp_line2 = v.findViewById(R.id.pp_line2);
        TextView edit = (TextView) v.findViewById(R.id.pp_edit);
        edit.setOnClickListener(this);
        TextView delete = (TextView) v.findViewById(R.id.pp_delete);
        delete.setOnClickListener(this);
        TextView share = (TextView) v.findViewById(R.id.pp_share);
        share.setOnClickListener(this);
        boolean userStatus = getIntent().getBooleanExtra("userStatus", false);
        if (mCurStatus.getPublishUser() != null && mCurStatus.getPublishUser().getUserid() == application.getCurID() || userStatus) {
            window = new PopupWindow(v, UIHelper.dip2px(StatusDetailActivity.this, 80), UIHelper.dip2px(StatusDetailActivity.this, 120));
        } else {
            window = new PopupWindow(v, UIHelper.dip2px(StatusDetailActivity.this, 80), UIHelper.dip2px(StatusDetailActivity.this, 40));
            edit.setVisibility(View.GONE);
            delete.setVisibility(View.GONE);
            pp_line1.setVisibility(View.GONE);
            pp_line2.setVisibility(View.GONE);
        }
        window.setAnimationStyle(R.style.pp_AnimationPreview);
        window.setTouchable(true);
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        window.showAsDropDown(parent);
    }

    // 删除该条动态
    private void doDeleteStatus() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(mCurStatus.getEid()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynDeleteEvent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resDelete = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resDelete.getCode())) {
                            Intent mIntent = new Intent(ACTIONs.actionStatus);
                            // 同步删除动态
                            mIntent.putExtra(ACTIONs.IsAdd, false);
                            mIntent.putExtra(ACTIONs.StatusId, mCurStatus.getEid());
                            sendBroadcast(mIntent);
                            sendBroadcast(new Intent(ACTIONs.actionGridWallUpdate));
                            finish();
                            if (getIntent().getBooleanExtra("detail", false)) {
                                sendBroadcast(new Intent(ACTIONs.McardDetailFinish));
                            }
                        } else {
                            showToast("删除失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(MyReceiver);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
